﻿using System;
using System.Threading;

namespace Wp7Tools.Util {
	public class Semaphore : IDisposable {
		private int _max, _current;
		private AutoResetEvent _sync = new AutoResetEvent(false);

		public Semaphore(int max) {
			_max = max;
		}

		public void Run(Action action) {
			try {
				if (Interlocked.Increment(ref _current) > _max) {
					_sync.WaitOne();
				}
				action.Invoke();
			}
			finally {
				_sync.Set();
				Interlocked.Decrement(ref _current);
			}
		}

		public void Dispose() {
			try {
				_sync.Dispose();				
			}
			catch{}
		}
	}
}